<style>
  .avatar{
    width: 145px;
    height: 145px;
  }
</style>
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品ID" prop="goodsId">
        <el-input
          v-model="queryParams.goodsId"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['batch:batch:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['batch:batch:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['batch:batch:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['batch:batch:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="batchList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="商品ID" align="center" prop="goodsId" />
       <el-table-column label="商品名称" align="center" prop="dtsGoods.name" />
      <el-table-column label="商品图片" align="center" prop="dtsGoods.picUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.dtsGoods.picUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="秒杀批次" align="center" prop="seckillBatch" />
      <el-table-column label="总数" align="center" prop="total" />
      <el-table-column label="剩余数量" align="center" prop="remainingQuantity" />
      <el-table-column label="是否结束" align="center" prop="conclude" >
        <template slot-scope="scope">
          {{scope.row.conclude==1 ? "结束":"否"}}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="starttime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.starttime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="ClosingTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ClosingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['batch:batch:edit']"
            v-show="scope.row.conclude==0"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleconclude(scope.row)"
            v-hasPermi="['batch:batch:edit']"
            v-show="scope.row.conclude==0"
          >结束</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['batch:batch:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改秒杀商品列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body @close="caca">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="商品名称" prop="goodsId" >
          <el-select v-model="form.goodsId" @change="handleGoodsIdChange(form.goodsId)">
            <el-option v-for="goods in GoodsList"
                       :key="goods.id"
                       :value="goods.id"
                       :label="goods.name">
                         {{goods.name}}
                         <image-preview :src="goods.picUrl" style="margin-left: 40px;float: right;" :width="25" :height="25"/>
                       </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="秒杀批次" prop="seckillBatch">
            <el-select v-model="form.seckillBatch" placeholder="请选择秒杀批次">
              <el-option label="00:00" value="00:00"></el-option>
              <el-option label="10:00" value="10:00"></el-option>
              <el-option label="12:00" value="12:00"></el-option>
              <el-option label="18:00" value="18:00"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="开始时间" prop="starttime">
          <el-date-picker clearable
            v-model="form.starttime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="ClosingTime">
          <el-date-picker clearable
            v-model="form.ClosingTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结束时间" prop="seckillBatch">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否可重复秒杀">
          <template>
            <el-radio v-model="form.seckill" :label="0">允许</el-radio>
            <el-radio v-model="form.seckill" :label="1">不允许</el-radio>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <el-table :data="GoodsProductListZS" border height="400">
        <!-- 货品规格 -->
        <el-table-column
          label="货品规格"
          align="center"
          prop="specifications"
        />

        <!-- 货品售价 -->
        <el-table-column
          label="货品售价"
          align="center"
          prop="price"
        />

        <!-- 货品数量 -->
        <el-table-column
          label="货品数量"
          align="center"
          prop="number"
        />

        <!-- 秒杀价 -->
        <el-table-column
          label="秒杀价"
          align="center"
          prop="flashSaleJiaGe"
        />

>

        <!-- 秒杀数量 -->
        <el-table-column
          label="秒杀数量"
          align="center"
          prop="miaoshashuliang"
        />


        <!-- 货品图片 -->
        <el-table-column
          label="货品图片"
          align="center"
          width="120"
        >
          <template #default="scope">
            <img
              :src="scope.row.url"
              style="width: 60px; height: 60px; object-fit: cover"
            >
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          align="center"
          width="150"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
            >
              设置
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

   <el-dialog :title="biaoti" :visible.sync="xian"  width="500px" >
     <el-form :model="GoodsProductXiangQ" ref="GoodsProductXiangQ" label-width="100px" :rules="yanz">
       <el-form-item label="货品规格列">
         <el-input v-model="GoodsProductXiangQ.specifications" disabled></el-input>
       </el-form-item>

       <el-form-item label="秒杀价" prop="flashSaleJiaGe">
         <!-- 使用v-model.number并改进正则表达式验证 -->
         <el-input
           type="text"
           v-model="GoodsProductXiangQ.flashSaleJiaGe"
           @input="validatePrice($event, 'flashSaleJiaGe')"
         />
       </el-form-item>

      <!-- <el-form-item label="秒杀数量">
         <!-- 添加v-model.number确保数值类型 -->
        <!-- <el-input v-model.number="GoodsProductXiangQ.miaoshashuliang" />
       </el-form-item> -->

       <el-form-item label="秒杀数量" prop="miaoshashuliang">
         <el-input
           v-model.number="GoodsProductXiangQ.miaoshashuliang"
           @change="validateSeckillQuantity"
         />
         <div v-if="quantityError" style="color: red; font-size: 12px;">
           {{ quantityError }}
         </div>
       </el-form-item>

       <el-form-item label="货品图片">
         <el-upload
           class="avatar-uploader"
           action="https://http://localhost/popularize/ad"
           :show-file-list="false"
           :on-success="handleAvatarSuccess"
           :before-upload="beforeAvatarUpload">
           <img v-if="GoodsProductXiangQ.url" :src="GoodsProductXiangQ.url" class="avatar">
           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
         </el-upload>
       </el-form-item>
     </el-form>
     <div slot="footer" class="dialog-footer">
       <el-button type="primary" @click="submitForm1">确 定</el-button>
       <el-button @click="cancel1">取 消</el-button>
     </div>
   </el-dialog>
  </div>
</template>
<style>
  .text {
      font-size: 14px;
    }

    .item {
      padding: 18px 0;
    }
</style>

<script>
import { listBatch, getBatch, delBatch, addBatch, updateBatch, getProductId,checkProductInSeckill} from "@/api/popularize/batch";
import {listGoods1,listProduct,listProductXiangQ} from "@/api/good/commodity/goods";

export default {
  name: "Batch",
  data() {
    return {
       quantityError: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 秒杀商品列表表格数据
      batchList: [],
      GoodsList:[],
      GoodsProductList:[],
      GoodsProductXiangQ:{
          id: 0,
          goodsId: 0,
          specifications: null,
          price: 0,
          number: 0,
          url: null,
          addTime: null,
          updateTime: null,
          deleted: 0,
          selected: null,
          dtsSeckillBatch: null,
          flashSaleJiaGe: 0,
          miaoshashuliang: 0
      },
      GoodsProductListZS:[],
      //根据商品的规格id获取的秒杀价格
      GoodsProductflashSalePrice:[],
      //商品规格id
      productIdList:[],
      biaoti:"设置秒杀货品",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示弹出层2
      xian:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsId: [
            { required: true, message: "请选择商品", trigger: "change" }
          ],
          seckillBatch: [
            { required: true, message: "请选择秒杀批次", trigger: "change" }
          ],
          starttime: [
            { required: true, message: "请选择开始时间", trigger: "change" }
          ],
          ClosingTime: [
            { required: true, message: "请选择结束时间", trigger: "change" }
          ],
          seckill: [
            { required: true, message: "请选择是否可重复秒杀", trigger: "change" }
          ]
      },
      yanz:{
        flashSaleJiaGe: [
                    {
                      validator: (rule, value, callback) => {
                        if (isNaN(Number(value))) {
                          callback(new Error('当前价格必须为数字'));
                        } else {
                          callback();
                        }
                      },
                      trigger: 'blur'
                    }
                  ],
      }
    };
  },
  created() {
    this.getList();
    this.getGoods();
  },
  methods: {
    validateSeckillQuantity() {
      if (this.GoodsProductXiangQ.miaoshashuliang > this.GoodsProductXiangQ.number) {
        this.quantityError = "秒杀数量不能大于库存数量";
        return false;
      } else if (this.GoodsProductXiangQ.miaoshashuliang <= 0) {
        this.quantityError = "秒杀数量必须大于0";
        return false;
      } else {
        this.quantityError = "";
        return true;
      }
    },
     validatePrice(event, field) {
        // 获取输入值并移除所有非数字和非小数点字符
        let value = event.target.value.replace(/[^0-9.]/g, '');
        console.log(value);
        // 确保最多只有一个小数点
        const dotIndex = value.indexOf('.');
        if (dotIndex !== -1) {
          value = value.substring(0, dotIndex + 1) + value.substring(dotIndex + 1).replace(/\./g, '');
        }

        // 限制小数点后最多两位
        const parts = value.split('.');
        if (parts.length > 1 && parts[1].length > 2) {
          parts[1] = parts[1].substring(0, 2);
          value = parts.join('.');
        }

        // 更新绑定值
        this.$set(this.GoodsProductXiangQ, field, value ? parseFloat(value) : null);
        event.target.value = value;
      },
    handleGoodsIdChange(goodsId) {
       this.getGoodsProduct(goodsId);
        },
    /** 查询秒杀商品列表列表 */
    getList() {
      this.loading = true;
      listBatch(this.queryParams).then(response => {
        this.batchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getGoods() {
      this.loading = true;
      listGoods1(this.queryParams).then(response => {
        this.GoodsList = response.rows;
      });
    },
    //查询商品规格
    getGoodsProduct(goodsId) {
       listProduct({id: goodsId}).then(response => {
         // 初始化商品规格列表
         this.GoodsProductList = response.rows;
         this.productIdList = this.GoodsProductList.map(item => item.id);

         // 如果有商品规格，获取对应的秒杀价格
         if (this.productIdList.length > 0) {
           getProductId(this.productIdList).then(response => {
             // 将秒杀价格数据转换为以product_id为键的对象，方便查找
             const flashSaleMap = {};
             response.data.forEach(item => {
               if (item.product_id) {
                 flashSaleMap[item.product_id] = item;
               }
             });

             // 合并商品规格数据和秒杀价格数据
             this.GoodsProductList = this.GoodsProductList.map(product => {
               const flashSaleInfo = flashSaleMap[product.id] || {};
               return {
                 ...product,
                 flashSaleJiaGe: flashSaleInfo.flashSalePrice || 0,
                 miaoshashuliang: flashSaleInfo.total || 0
               };
             });

             // 更新展示列表
             this.GoodsProductListZS = [...this.GoodsProductList];
             console.log("处理后的商品规格数据:", JSON.stringify(this.GoodsProductList, null, 2));
           });
         } else {
           // 如果没有商品规格，清空列表
           this.GoodsProductList = [];
           this.GoodsProductListZS = [];
         }
       });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.GoodsProductListZS=null;
      this.reset();
    },
    //取消按钮2
    cancel1() {
      this.xian = false;
      // this.reset();
    },
    submitForm1() {
       if (!this.validateSeckillQuantity()) {
          return;
        }

      this.$refs.GoodsProductXiangQ.validate((valid) => {
        if (valid) {
          // 查找对应商品规格在列表中的索引
           const index = this.GoodsProductListZS.findIndex(item => item.id === this.GoodsProductXiangQ.id);

           if (index !== -1) {
             // 更新商品规格列表中的数据
             this.GoodsProductListZS.splice(index, 1, JSON.parse(JSON.stringify(this.GoodsProductXiangQ)));

             // 这里应该调用API保存数据到服务器
             // 示例：saveProductFlashSaleInfo(this.GoodsProductXiangQ).then(...)

             this.$message.success('保存成功');
             this.xian = false;
           } else {
             this.$message.error('未找到对应商品规格');
           }
        } else {
          this.$message.error('表单验证不通过，请检查输入内容');
          return false;
        }
      })


    },
    //点击x的时候
    caca(){
      this.open = false;
      this.GoodsProductListZS=null;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsId: null,
        seckillBatch: null,
        total: null,
        remainingQuantity: null,
        conclude: null,
        starttime: null,
        ClosingTime: null,
        delete: null,
        seckill: null,
        product_id:null,
        flashSalePrice:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //规格详情
    handleEdit(row){
      console.log(this.GoodsProductListZS);
        console.log(row.id);
        this.xian = true;

        // 找到对应商品规格
        const product = this.GoodsProductListZS.find(item => item.id === row.id);

        if (product) {
          // 创建数据的深拷贝，而不是直接引用
          this.GoodsProductXiangQ = JSON.parse(JSON.stringify(product));
          console.log("编辑的数据:", JSON.stringify(this.GoodsProductXiangQ, null, 2));
        }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加秒杀商品列表";
    },
    //修改结束状态
    handleconclude(row){
      const id = row.id;
      const Conclude=1;
      console.log(JSON.stringify(row, null, 2));
      // let param = {
      //   id: id,
      //   conclude: Conclude
      // }
      let param = {
        id: id,
        goodsId: row.goodsId,
        seckillBatch: row.seckillBatch,
        conclude: Conclude
      }

      updateBatch(param).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBatch(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改秒杀商品列表";
        this.getGoodsProduct(response.data.dtsGoods.id);
        console.log(JSON.stringify(response.data, null, 2));
      });
    },
    /** 提交按钮 */
    submitForm() {
        this.$refs["form"].validate(valid => {
                if (valid) {
                  // 检查是否选择了商品
                  if (!this.form.goodsId) {
                    this.$message.warning("请选择商品");
                    return;
                  }

                  // 检查是否有商品规格数据
                  if (!this.GoodsProductListZS || this.GoodsProductListZS.length === 0) {
                    this.$message.warning("该商品没有可设置的规格");
                    return;
                  }

                  // 收集所有商品规格的秒杀信息，过滤掉未设置的数据
                  const seckillItems = this.GoodsProductListZS
                    .filter(item => item.flashSaleJiaGe > 0 && item.miaoshashuliang > 0)
                    .map(item => ({
                      productId: item.id,
                      flashSalePrice: item.flashSaleJiaGe,
                      remainingQuantity: item.miaoshashuliang,
                      specifications: item.specifications
                    }));

                  // 检查是否有有效的秒杀商品
                  if (seckillItems.length === 0) {
                    this.$message.warning("请至少设置一个商品规格的秒杀价和秒杀数量");
                    return;
                  }

                  // 准备提交的数据
                  const formData = {
                    ...this.form,
                    seckillItems // 包含所有规格的秒杀信息
                  };

                  // 提取所有product_id用于查询
                  const productIds = seckillItems.map(item => item.productId);

                  // 调用API查询这些product_id在秒杀表中是否存在
                  checkProductInSeckill(productIds).then(response => {
                    // response.data应该是一个对象，键为product_id，值为是否存在(true/false)
                    const existMap = response.data;

                    // 分割需要新增和需要更新的商品规格
                    const itemsToAdd = [];
                    const itemsToUpdate = [];
                    seckillItems.forEach(item => {
                        // 不存在，添加到新增列表
                        itemsToAdd.push(item);
                    });

                    // 处理新增和更新的Promise数组
                    const promises = [];

                    // 如果有需要新增的项
                    if (0 == 0) {
                      const addData = {
                        ...formData,
                        seckillItems: itemsToAdd
                      };
                      console.log(JSON.stringify(addData, null, 2));
                      promises.push(addBatch(addData));
                    }

                    // 并行执行所有操作
                    Promise.all(promises).then(results => {
                      this.$modal.msgSuccess("操作成功");
                      this.open = false;
                      this.getList();
                    }).catch(error => {
                      this.$modal.msgError("操作失败: " + error.message);
                    }).finally(() => {
                      this.loading = false;
                    });
                  }).catch(error => {
                    this.$modal.msgError("查询失败: " + error.message);
                    this.loading = false;
                  });
                }
              });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除秒杀商品列表编号为"' + ids + '"的数据项？').then(function() {
        return delBatch(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('batch/batch/export', {
        ...this.queryParams
      }, `batch_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
